<template>
  <div>
    <el-card class="box-card" :body-style="{ padding: '15px',height:'150px'}">
      <el-form :inline="true" :model="keyword" ref="keyword" class="demo-form-inline">
        <el-form-item></el-form-item>
        <el-form-item label="采购名称" prop="orderName">
          <el-input clearable v-model="keyword.orderName" placeholder="请输入采购编号"></el-input>
        </el-form-item>
        <el-form-item label="采购日期" prop="orderTime" style="margin-left: 30px;">
          <el-date-picker
           
            v-model="keyword.date"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dataFormat"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="到货日期" prop="arrivalTime" style="margin-left: 12px;">
          <el-date-picker
            v-model="keyword.arrivalTime"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            
          ></el-date-picker>
        </el-form-item>

        <el-form-item style="float: right;">
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button @click="resetForm('keyword')" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card box-card2">
      <div style="margin-top: -15px;margin-bottom: 10px;">
        <el-button type="primary" icon="el-icon-circle-plus" @click=" openAddDialog">新增</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="delBatch">批量删除</el-button>
        <el-button
          type="primary"
          icon="el-icon-upload2"
          @click=" dialogExcelVisible=true"
        >导入采购明细</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click=" downloadExcel"
        >导出采购明细</el-button>
      </div>
      <!-- 导入订单明细 -->
      <el-dialog title="上传采购明细" :visible.sync="dialogExcelVisible" width="400px">
        <el-upload
          class="upload-demo"
          drag
          action="http://localhost:8080/wms/order/upload/excel"
          accept=".xlsx, .xls"
          :on-success="uploadExcelSuccess"
          :on-error="uploadExcelError"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">只能上传.xlsx,.xls文件，且不超过500kb</div>
        </el-upload>
      </el-dialog>
      <!-- 新增框 -->
      <el-dialog title="新增采购订单" :visible.sync="dialogFormVisible">
        <el-form :model="order" ref="order">
          <el-form-item
            label="订单编号"
            label-width="100px"
            prop="orderUid"
            style="display: inline-block; float: left; "
          >
            <el-input v-model="order.orderUid" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <el-form-item
            label="订单名称"
            label-width="90px"
            prop="orderName"
            style="display: inline-block;"
          >
            <el-input v-model="order.orderName" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <el-form-item
            label="品牌"
            label-width="100px"
            prop="brand"
            style="display: inline-block; float: left; "
          >
            <el-input v-model="order.brand" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <el-form-item label="规格型号" label-width="90px" prop="spe" style="display: inline-block;">
            <el-input v-model="order.spe" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <br />
          <el-form-item
            label="单位"
            label-width="100px"
            prop="unit"
            style="display: inline-block; float: left; "
          >
            <el-input v-model="order.unit" autocomplete="off" style="width: 120px;"></el-input>
          </el-form-item>
          <el-form-item
            label="采购数量"
            label-width="100px"
            prop="quantity"
            style="display: inline-block; margin-left: 50px;"
          >
            <el-input-number v-model="order.quantity" :min="0" :max="20"></el-input-number>
          </el-form-item>
          <br />
          <el-form-item
            label="计划使用项目"
            label-width="100px"
            prop="userItem"
            style="display: inline-block; float: left; "
          >
            <el-input v-model="order.userItem" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <el-form-item label="存入仓库" prop="ware" label-width="90px" style="display: inline-block;">
            <el-input v-model="order.ware" autocomplete="off" style="width: 260px;"></el-input>
          </el-form-item>
          <br />
          <div>
            <p style="width: 100px; height:50px;float:left;font-Size:15px;">图片上传</p>
            <div style="display: inline-block;">
              <img :src="fileSrc" width="200px" height="180px" />
            </div>
            <div style="float: left;">
              <el-upload
                label="文件上传"
                prop="pic"
                drag
                action
                :http-request="uploadFile"
                :on-change="handleChange"
                multiple
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
            </div>
          </div>

          <br />
          <el-form-item
            style="display: inline-block;float:left; "
            label="采购日期"
            prop="orderTime"
            label-width="90px"
          >
            <el-date-picker v-model="order.orderTime" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item
            label="到货日期"
            prop="arrivalTime"
            label-width="90px"
            style="display: inline-block;"
          >
            <el-date-picker v-model="order.arrivalTime" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancle('order')">取 消</el-button>
          <el-button type="primary" @click="add('order')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 详情框 -->
      <el-dialog title="详情信息" :visible.sync="dialogTableVisible">
        <el-table
          :data="orderDetail"
          border
          width="500px"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
        >
          <el-table-column prop="orderName" label="采购名称" width="180"></el-table-column>
          <el-table-column property="brand" label="品牌" width="150"></el-table-column>
          <el-table-column property="spe" label="规格型号"></el-table-column>
          <el-table-column property="unit" label="单位"></el-table-column>
          <el-table-column property="quantity" label="采购数量"></el-table-column>
          <el-table-column property="uquantity" label="未到数量"></el-table-column>
          <el-table-column property="aquantity" label="已到数量"></el-table-column>
          <el-table-column property="userItem" label="计划使用项目" width="180px"></el-table-column>
          <el-table-column property="ware" label="存入仓库" width="180px"></el-table-column>
          <el-table-column label="货物图片" width="180px">
            <img :src="picS" width="100px" height="100px" />
          </el-table-column>
        </el-table>
      </el-dialog>
      <el-table
        v-loading="loading"
        :data=" orderList"
        style="width: 100%;"
        height="370"
        border
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
        
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="orderUid" label="采购编号" :show-overflow-tooltip="true" width="200"></el-table-column>
        <el-table-column prop="orderTime" label="采购日期" width="160"></el-table-column>
        <el-table-column prop="arrivalTime" label="预计到货日期" width="160"></el-table-column>
        <el-table-column prop="arrivalConfirmer" label="确认收货人" width="150"></el-table-column>
        <el-table-column prop="arrivalStatus" width="130" label="到货状态">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.arrivalStatus=='1'?'blue':scope.row.arrivalStatus=='2'?'danger':scope.row.arrivalStatus=='3'?'warning':'info'"
            >{{scope.row.arrivalStatus=='1'?'全部到货':scope.row.arrivalStatus=='2'?'未到货':scope.row.arrivalStatus=='3'?'部分到货':'未知'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" width="180" label="创建日期"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="details(scope.row)">详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-claim"
              @click="receipt(scope.row)"
            >确认收货</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 确认收货 -->
    <el-dialog title="确认收货" :visible.sync="dialogReceVisible" width="400px">
      <el-form ref="order" :model="order">
        <el-form-item label="剩余未到" label-width="100px" prop="aquantity">
          <el-input clearable v-model="order.uquantity" placeholder="请输入到货数量" disabled></el-input>
        </el-form-item>
        <el-form-item label="到货数量" label-width="100px" prop="aquantity">
          <el-input clearable v-model="order.aquantity" placeholder="请输入到货数量"></el-input>
        </el-form-item>
        <el-form-item label="确认人" label-width="100px" prop="arrivalConfirmer">
          <el-select v-model="order.arrivalConfirmer" placeholder="收货人" style="width: 260px;">
            <el-option v-for="name in nameList" :label="name.username" :value="name.username"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Recancle('order')">取 消</el-button>
        <el-button type="primary" @click="queren('order')">确 定</el-button>
      </div>
    </el-dialog>
    <el-card class="box-card" :body-style="{ padding: '15px',height:'50px'}">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[ 5,10,15,20]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import {
  getList,
  addOrder,
  delOrderById,
  delBatch,
  uploadPicture,
  detail,
  getName,
  updateAr
} from "@/api/order.js";

export default {
  name: "PO",
  data() {
    return {
      // loading: true,
      orderList: [],
      orderDetail: [],
      nameList: [],

      keyword: {
        orderTime: "",
        date: "",
        starTime: "",
        endTime: "",
      },
      loading: true,
      fileSrc: "",
      file: null,
      order: {
        pic: null,
        orderId: null,
        orderUid: null,
        orderName: null,
        brand: null,
        spe: null,
        unit: null,
        ware: null,
        quantity: null,
        uquantity: null,
        aquantity: null,
        orderTime: null,
        arrivalTime: null,
        cargoPic: null,
        userItem: null,
        arrivalConfirmer: null,
        deliveryTime: null
      },
      orderX: {
        pic: null,
        orderId: null,
        orderUid: null,
        orderName: null,
        brand: null,
        spe: null,
        unit: null,
        ware: null,
        uquantity: null,
        aquantity: null,
        quantity: null,
        orderTime: null,
        arrivalTime: null,
        cargoPic: null,
        userItem: null
      },
      picS: "",
      total: 0,
      currentPage: 1, // 当前页面
      total: 0, // 总条数
      pageNum: 1, // 当前页面
      pageSize: 5, // 每页大小
      dialogFormVisible: false, // 新增
      dialogExcelVisible: false, // 导入订单明细
      dialogTableVisible: false, // 详情
      dialogReceVisible: false, // 确认收货
      idList: [],
      imageUrl: "",
      url: "https://xiaoze-taitai.oss-cn-beijing.aliyuncs.com/"
    };
  },
  methods: {
    dataFormat(picker){
      this.keyword.starTime = picker[0]
      this.keyword.endTime = picker[1]
    },
    // 导出Excel
    downloadExcel(){
      this.$confirm("确定导出Excel吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.location.href = "http://localhost:8080/wms/order/download/excel";
      }).catch(() => {
        this.$message({
          type: "info",
          message: "取消导出"
        });
      })
    },
    // excel上传成功
    uploadExcelSuccess() {
      this.$message({
        type: "success",
        message: "上传成功"
      });
      this.dialogExcelVisible = false;
      this.findAll();
    },
    // excel上传失败
    uploadExcelError() {
      this.$message({
        type: "error",
        message: err
      });
    },
    //确认人
    queren(forname) {
      if (this.order.quantity < this.order.aquantity) {
        this.$message({
          type: "error",
          message: "到货数量不能大于采购数量!"
        });
        return;
      }
      console.log("确认后", this.order);
      updateAr(this.order).then(res => {
        if(res.data == false){
          this.$message({
            type: "error",
            message: "到货数量不能大于采购数量!"
          });
        }else{
          this.$message({
            type: "success",
            message: "收货成功!"
          });
        }
        this.dialogReceVisible = false;
        this.findAll();
        this.$refs[forname].resetFields();
      });
    },
    Recancle(forname) {
      this.$refs[forname].resetFields();
      this.dialogReceVisible = false;
    },
    // 确认收货
    receipt(row) {
      this.order = row;
      this.dialogReceVisible = true;
      getName().then(res => {
        this.nameList = res.data;
      });
    },
    // 取消默认清空
    cancle(froname) {
      this.$refs[froname].resetFields();
      this.dialogFormVisible = false;
      this.fileSrc = "";
    },
    handleChange(file) {
      this.file = file.raw;
    },
    // 上传图片
    uploadFile() {
      const file = this.file;
      const formData = new FormData();
      formData.append("file", file);
      uploadPicture(formData).then(res => {
        console.log(res);
        this.$message({
          message: "上传成功",
          type: "success"
        });
        // 回显
        this.fileSrc = this.url + res.data;
        this.order.cargoPic = res.data;
        console.log(this.order);
        console.log("fileSrc", this.fileSrc);
      });
    },
    findAll() {
      getList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        startTime: this.keyword.starTime,
        endTime: this.keyword.endTime
      }).then(res => {
        console.log(res);
        this.orderList = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.findAll();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.findAll();
    },
    // 新增
    openAddDialog() {
      this.dialogFormVisible = true;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 详情
    details(row) {
      this.dialogTableVisible = true;
      this.orderX = row;
      detail({
        id: this.orderX.orderId
      }).then(res => {
        console.log(res.data);
        this.orderDetail = res.data;
        console.log(res.data[0].cargoPic);
        this.picS = this.url + res.data[0].cargoPic;
        console.log(this.picS);
      });
    },
    // 添加订单
    add(forname) {
      this.order.uquantity = this.order.quantity;
      addOrder(this.order).then(res => {
        if (res.code == 20000) {
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.findAll();
          this.fileSrc = "";
          this.$refs[forname].resetFields();
          this.dialogFormVisible = false;
        } else {
          this.$message({
            message: res.msg,
            type: "error"
          });
        }
      });
    },
    // 根据id删除
    handleDelete(index, row) {
      console.log(row.orderId);
      this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delOrderById({
            id: row.orderId
          })
            .then(res => {
              if (res.code == 20000) {
                this.$message({
                  message: "删除成功",
                  type: "success",
                  duration: 1000
                });
                this.findAll();
              }
            })
            .catch(err => {
              this.$message({
                message: "删除失败",
                type: "error",
                duration: 1000
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    handleSelectionChange(val) {
      this.idList = [];
      this.multipleSelection = val;
      for (var i = 0; i < this.multipleSelection.length; i++) {
        let user = this.multipleSelection[i];
        this.idList.push(user.orderId);
      }
    },
    // 批量删除
    delBatch() {
      this.$confirm("是否删除选中的订单？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const idString = this.idList.join(",");
          delBatch({
            ids: idString
          })
            .then(res => {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1000
              });
              this.findAll();
            })
            .catch(err => {
              this.$message({
                message: "删除失败",
                type: "error",
                duration: 1000
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 重置input框
    resetForm(fromname) {
      this.findAll();
      this.$refs[fromname].resetFields();
    },
    search() {
      this.findAll();
    }
  },

  mounted() {
    this.findAll();
  }
};
</script>

<style>
.box-card {
  width: 100%;
  margin-top: 10px;
}
.box-card3 {
  height: 100px;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-left: 80px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>